package cn.net.xyan.easy.webapp.base.dao;

import cn.net.xyan.easy.spring.jpa.utils.EasyJpaRepository;
import cn.net.xyan.easy.webapp.base.entity.Permission;
import cn.net.xyan.easy.webapp.base.entity.PermissionGroup;
import cn.net.xyan.easy.webapp.base.entity.SystemUser;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * Created by xiashenpin on 16/1/23.
 */
public interface PermissionDao extends EasyJpaRepository<Permission,String> {
    @Query("select distinct  p from Permission p   " +
            "where p.sequence in (select p.sequence from Permission p left join p.users u1 where u1 = ?1 ) or " +
            "p.sequence in  (select p.sequence from Permission p inner join  p.groups g left join g.users u2 where u2 = ?1 and g.status.abandon = false )  ")
    List<Permission> findAllPermissionForUser(SystemUser user);

    @Query("select distinct  p from Permission p  right join  p.groups g where g in ?1 ")
    List<Permission> findAllPermissionForGroups(List<PermissionGroup> groups);

    Permission findByPermission(String permission);

    @Query("select distinct  p from Permission p   " +
            "where "
            +"p.sequence in (select p.sequence from Permission p left join p.users u1 where u1 = ?1 and p = ?2 ) or " +
            "p.sequence in  (select p.sequence from Permission p inner join  p.groups g left join g.users u2 where u2 = ?1 and g.status.abandon = false and p = ?2)  ")
    Permission checkUserHasPermission(SystemUser user,Permission permission);

    @Query("select distinct  p from Permission p   " +
            "where "
            +"p.sequence in (select p.sequence from Permission p left join p.users u1 where u1 = ?1 and p in ?2 ) or " +
            "p.sequence in  (select p.sequence from Permission p inner join  p.groups g left join g.users u2 where u2 = ?1 and g.status.abandon = false and p in ?2)  ")
    List<Permission> checkUserHasPermissions(SystemUser user,List<Permission> permissions);

    @Query("select p from Permission p where p not in ?1")
    List<Permission> findPermissionNotIn(List<Permission> permissions);
}
